package com.example.wechat;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.webkit.MimeTypeMap;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FileUploadUtils {
    private static final String TAG = "FileUploadUtils";
    private static final String UPLOAD_URL = "http://your-server.com/upload";
    private static final OkHttpClient client = new OkHttpClient();

    public interface UploadCallback {
        void onProgress(int progress);
        void onSuccess(String url);
        void onError(String error);
    }

    public static void uploadFile(Context context, Uri fileUri, String fileType, UploadCallback callback) {
        try {
            File file = createTempFileFromUri(context, fileUri);
            if (file == null) {
                callback.onError("无法创建临时文件");
                return;
            }

            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(),
                            new ProgressRequestBody(
                                    RequestBody.create(MediaType.get(fileType), file),
                                    (bytesWritten, contentLength) -> {
                                        int progress = (int) (bytesWritten * 100 / contentLength);
                                        callback.onProgress(progress);
                                    }))
                    .build();

            Request request = new Request.Builder()
                    .url(UPLOAD_URL)
                    .post(requestBody)
                    .build();

            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    Log.e(TAG, "上传失败", e);
                    callback.onError("上传失败: " + e.getMessage());
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String url = response.body().string();
                        callback.onSuccess(url);
                    } else {
                        callback.onError("上传失败: " + response.code());
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "上传失败", e);
            callback.onError("上传失败: " + e.getMessage());
        }
    }

    private static File createTempFileFromUri(Context context, Uri uri) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) {
                return null;
            }

            File tempFile = new File(context.getCacheDir(), "upload_" + System.currentTimeMillis());
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();

            return tempFile;
        } catch (IOException e) {
            Log.e(TAG, "创建临时文件失败", e);
            return null;
        }
    }

    private static String getMimeType(Uri uri) {
        String extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
} 